package org.imlinker.gui;

import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

public class WindowSaver {

	private static String path;

	public static void setPath(String path) {
		WindowSaver.path = path + File.separator + "config" + File.separator
				+ "window.prop";
	}

	public static void restoreLocation(JFrame window) {
		Properties settings = getPreperties();

		String name = window.getName();
		int x = getInt(settings, name + ".x", -1);
		int y = getInt(settings, name + ".y", -1);

		if (x > -1 && y > -1) {
			window.setLocation(x, y);
		}
	}

	public static WindowListener getListener() {

		WindowListener listener = new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				Point point = e.getWindow().getLocation();
				String name = e.getWindow().getName();

				Properties settings = getPreperties();
				settings.put(name + ".x", String.valueOf(point.x));
				settings.put(name + ".y", String.valueOf(point.y));

				savePreperties(settings);
			}
		};

		return listener;
	}

	private static Properties getPreperties() {
		Properties settings = new Properties();

		try {
			settings.load(new FileInputStream(path));
		} catch (FileNotFoundException fnfe) {
			try {
				settings.store(new FileOutputStream(path), "");
			} catch (FileNotFoundException e1) {
			} catch (IOException e1) {
			}
		} catch (IOException ioe) {
		}

		return settings;
	}

	private static void savePreperties(Properties settings) {
		try {
			settings.store(new FileOutputStream(path), "");
		} catch (FileNotFoundException e1) {
		} catch (IOException e1) {
		}
	}

	private static int getInt(final Properties settings, final String name,
			final int i) {
		String v = settings.getProperty(name);
		if (v == null) {
			return i;
		}

		return Integer.parseInt(v);
	}
}
